package com.forever.thread;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockTest {

	private Lock lock = new ReentrantLock();
	private int value = 0;

	public Integer inc() {
		lock.lock();
		try {
			value++;
			return value;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
		return null;
	}

	private static boolean stopRequested;

	public static void main(String[] args) throws InterruptedException {
		Thread backgroundThread = new Thread(new Runnable() {
			public void run() {
				int i = 0;
				while (!stopRequested) {
					i++;
				}
			}
		});

		backgroundThread.start();

		TimeUnit.SECONDS.sleep(1);
		stopRequested = true;
	}

	/**
	 * 计数器
	 * 
	 * @param times
	 * @param task
	 * @return
	 * @throws InterruptedException
	 */
	public long timecost(final int times, final Runnable task) throws InterruptedException {
		if (times <= 0) {
			throw new IllegalArgumentException();
		}
		final CountDownLatch startLatch = new CountDownLatch(1);
		final CountDownLatch overLatch = new CountDownLatch(times);
		for (int i = 0; i < times; i++) {
			new Thread(new Runnable() {
				public void run() {
					try {
						startLatch.await();
						task.run();
					} catch (InterruptedException ex) {
						Thread.currentThread().interrupt();
					} finally {
						overLatch.countDown();
					}
				}
			}).start();
		}
		long start = System.nanoTime();
		startLatch.countDown();
		overLatch.await();
		return System.nanoTime() - start;
	}
}